package ru.usu.gv.uicomponents.listener;

import ru.usu.gv.core.GraphCanvas;
import ru.usu.gv.graph.Graph;
import ru.usu.gv.uicomponents.UIGraph;

import java.util.ArrayList;
import java.util.List;

/**
 * @author spupyrev
 * 31.10.2008
 */
public class GraphChangeListenerColection
{
	private List<IChangeListener> listeners = new ArrayList<IChangeListener>();

	public void doChange(Object sender)
	{
		if (GraphCanvas.getInstance() == null || !isActiveSender(sender))
			return;

		for (IChangeListener listener : listeners)
			listener.doChange(sender);
	}

	private boolean isActiveSender(Object sender)
	{
		UIGraph currentGraph = GraphCanvas.getInstance().getCurrentGraph();
		if (currentGraph == null)
		{
			return false;
		}

		if (sender instanceof Graph)
		{
			if (!sender.equals(currentGraph.getGraph()))
				return false;
		}
		else if (sender instanceof UIGraph)
		{
			if (!sender.equals(currentGraph))
				return false;
		}
		else
		{
			//throw new RuntimeException("Unknown sender");
		}
		return true;
	}

	public void addListener(IChangeListener listener)
	{
		listeners.add(listener);
	}

	public void removeListener(IChangeListener listener)
	{
		listeners.remove(listener);
	}
}
